package com.arrake.pojo;


import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipOutputStream;

import java.io.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Docx {
    private String preDocument;
    private String sufDocument;

    private static volatile Docx docx;

    public static Docx getInstanceDocx() {
        if (docx == null) {
            synchronized (Docx.class) {
                if (docx == null) {
                    docx = new Docx();
                }
            }

        }
        return docx;
    }

    public void cleanInstanceDocx() {
        docx = new Docx();
    }

    public Docx() {
        preDocument = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n" +
                "<w:document\n" +
                "    xmlns:wpc=\"http://schemas.microsoft.com/office/word/2010/wordprocessingCanvas\"\n" +
                "    xmlns:mc=\"http://schemas.openxmlformats.org/markup-compatibility/2006\"\n" +
                "    xmlns:o=\"urn:schemas-microsoft-com:office:office\"\n" +
                "    xmlns:r=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships\"\n" +
                "    xmlns:m=\"http://schemas.openxmlformats.org/officeDocument/2006/math\"\n" +
                "    xmlns:v=\"urn:schemas-microsoft-com:vml\"\n" +
                "    xmlns:wp14=\"http://schemas.microsoft.com/office/word/2010/wordprocessingDrawing\"\n" +
                "    xmlns:wp=\"http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing\"\n" +
                "    xmlns:w=\"http://schemas.openxmlformats.org/wordprocessingml/2006/main\"\n" +
                "    xmlns:w14=\"http://schemas.microsoft.com/office/word/2010/wordml\"\n" +
                "    xmlns:w10=\"urn:schemas-microsoft-com:office:word\"\n" +
                "    xmlns:w15=\"http://schemas.microsoft.com/office/word/2012/wordml\"\n" +
                "    xmlns:wpg=\"http://schemas.microsoft.com/office/word/2010/wordprocessingGroup\"\n" +
                "    xmlns:wpi=\"http://schemas.microsoft.com/office/word/2010/wordprocessingInk\"\n" +
                "    xmlns:wne=\"http://schemas.microsoft.com/office/word/2006/wordml\"\n" +
                "    xmlns:wps=\"http://schemas.microsoft.com/office/word/2010/wordprocessingShape\"\n" +
                "    xmlns:wpsCustomData=\"http://www.wps.cn/officeDocument/2013/wpsCustomData\" mc:Ignorable=\"w14 w15 wp14\">\n" +
                "    <w:body>\n";
        sufDocument = "    </w:body>\n" +
                "</w:document>\n";
    }


    public Docx addParagraph(DocxParagraph paragraph) {
        preDocument = preDocument + paragraph.getPreParagraph() + paragraph.getSufParagraph();
        return this;
    }


    public void createDocx(String filePath) throws Exception {
        String docx;
        String path = null;
        docx = preDocument + sufDocument;
        //创建document.xml文件

        OutputStream out = new FileOutputStream(new File("src\\main\\resources\\docxTemplate\\word\\document.xml"));
        PrintStream ps = new PrintStream(out);
        ps.println(docx);

        ps.close();
        out.close();
        //创建document.xml.rels文件
        RelationShip.getInstanceRelationShip().createRelationship();


        //压缩并修改，文件名
        File file = new File("src\\main\\resources\\docxTemplate");
        // 用于存放压缩文件的文件夹
        Matcher matcher1 = Pattern.compile("(.+\\\\.+)\\.").matcher(filePath);
        if (matcher1.find()) {
            filePath = matcher1.group(1) + "--未答";
        }
        File file3 = new File(filePath);
        Matcher matcher = Pattern.compile("[A-Z]:\\\\.*\\\\").matcher(file3.getAbsolutePath());
        while (matcher.find()) {
            path = matcher.group();
        }
        String generateFile = path + "FormatFile";

        File compress = new File(generateFile);
        // 如果文件夹不存在，进行创建
        if (!compress.exists()) {
            compress.mkdirs();
        }

        // 目的压缩文件
        String generateFileName = compress.getAbsolutePath() + File.separator + file3.getName() + ".docx";


        // 压缩输出流
        ZipOutputStream zipOutputStream = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(generateFileName)));

        generateFile(zipOutputStream, file, "");
        // 关闭 输出流

        zipOutputStream.close();
        //修改文件名
        File file1 = new File(generateFileName);
        File file2 = new File(file1.getParent() + File.separator + file3.getName() + ".docx");
        file1.renameTo(file2);
        System.out.println("生成文件位置：" + file1.getAbsolutePath());

//        清空media文件夹
        File file4 = new File("src\\main\\resources\\docxTemplate\\word\\media");
        File[] files = file4.listFiles();
        for (File file5 : files) {
            file5.delete();
        }
        File file6 = new File("src\\main\\resources\\docxTemplate\\word\\_rels\\document.xml.rels");
        file6.delete();
        File file7 = new File("src\\main\\resources\\docxTemplate\\word\\document.xml");
        file7.delete();
    }

    private static void generateFile(ZipOutputStream out, File file, String dir) throws Exception {

        // 当前的是文件夹，则进行一步处理
        if (file.isDirectory()) {
            //得到文件列表信息
            File[] files = file.listFiles();

            //将文件夹添加到下一级打包目录
            out.putNextEntry(new ZipEntry(dir + "/"));

            dir = dir.length() == 0 ? "" : dir + "/";

            //循环将文件夹中的文件打包
            for (int i = 0; i < files.length; i++) {
                generateFile(out, files[i], dir + files[i].getName());
            }

        } else { // 当前是文件

            // 输入流
            FileInputStream inputStream = new FileInputStream(file);
            // 标记要打包的条目
            out.putNextEntry(new ZipEntry(dir));
            // 进行写操作
            int len = 0;
            byte[] bytes = new byte[1024];
            while ((len = inputStream.read(bytes)) > 0) {
                out.write(bytes, 0, len);
            }
            // 关闭输入流
            inputStream.close();
        }

    }

    @Override
    public String toString() {
        return "Docx{" +
                "preDocument='" + preDocument + '\'' +
                ", sufDocument='" + sufDocument + '\'' +
                '}';
    }
}
